import sys
import json

import wave
import pyaudio
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QTextEdit
from PyQt5.QtGui import QPixmap, QPalette, QBrush
from PyQt5.QtCore import Qt, QFile, QTextStream
from PicGenerate import generatePic
from content.qianwen import generate_outline, generate_game_content
from text_to_speech import getTextWav

game_over = False
chat_history = []
last_choice = None
outline = None
tone = None


class SoundPlayer:
    def __init__(self, file_path):
        self.file_path = file_path

    def play(self):
        try:
            # 打开WAV文件
            wf = wave.open(self.file_path, 'rb')
            # 初始化PyAudio
            p = pyaudio.PyAudio()
            # 打开流
            stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                            channels=wf.getnchannels(),
                            rate=wf.getframerate(),
                            output=True)
            # 读取数据并播放
            data = wf.readframes(1024)
            while len(data) > 0:
                stream.write(data)
                data = wf.readframes(1024)
            stream.stop_stream()
            stream.close()
            p.terminate()
        except wave.Error as e:
            print(f"Wave file error: {e}")
        except pyaudio.PyAudioError as e:
            print(f"PyAudio error: {e}")
        except Exception as e:
            print(f"An unexpected error occurred: {e}")


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.wav_index = 0
        self.initUI()

    def initUI(self):
        self.setGeometry(475, 295, 1760-475, 1060-295)  # 设置窗口位置和大小
        self.setWindowTitle('游戏启动界面')

        # 设置初始背景
        self.original_pixmap = QPixmap('./img/bg.png')  # 替换为你的初始背景图片路径
        self.original_palette = QPalette()
        self.original_palette.setBrush(QPalette.Window, QBrush(self.original_pixmap.scaled(self.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)))
        self.setPalette(self.original_palette)



        #显示健康值等属性
        self.textedit = QTextEdit(self)
        self.textedit.setObjectName("PropertyBox")
        self.textedit.resize(200, 30)
        self.textedit.move(1000, 20)  # 设置输入框位置
        self.textedit.setReadOnly(True)  # 设置为只读
        self.textedit.hide()

        #显示故事
        self.story_edit = QTextEdit(self)
        # self.textedit.resize(height=300)
        self.story_edit.setObjectName("storyEdit")
        self.story_edit.move(100, 500)  # 设置输入框位置
        self.story_edit.setReadOnly(True)  # 设置为只读
        self.story_edit.hide()

        # 创建输入框
        self.name_input = QLineEdit(self)
        self.name_input.setPlaceholderText('输入角色姓名')
        self.name_input.resize(300, 60)
        self.name_input.move(250, 150)  # 设置输入框位置

        self.background_input = QLineEdit(self)
        self.background_input.setPlaceholderText('输入故事背景')
        self.background_input.resize(300, 60)
        self.background_input.move(750, 150)  # 设置输入框位置

        self.style_input = QLineEdit(self)
        self.style_input.setPlaceholderText('输入故事风格')
        self.style_input.resize(300, 60)
        self.style_input.move(250, 350)  # 设置输入框位置

        self.tone_input = QLineEdit(self)
        self.tone_input.setPlaceholderText('输入语言风格')
        self.tone_input.resize(300, 60)
        self.tone_input.move(750, 350)  # 设置输入框位置

        # 创建开始游戏按钮
        self.start_button = QPushButton('开始游戏', self)
        self.start_button.setObjectName("startButton")
        self.start_button.clicked.connect(self.startGame)
        self.start_button.resize(250, 80)
        self.start_button.move(525, 550)  # 设置按钮位置

        # 创建选项按钮并设置位置
        self.button1 = QPushButton('1', self)
        # self.button1.resize(100, 40)
        self.button1.clicked.connect(self.button_clicked1)
        self.button1.move(200, 200)  # 设置按钮1的位置
        self.button1.hide()

        self.button2 = QPushButton('2', self)
        # self.button2.resize(100, 40)
        self.button2.clicked.connect(self.button_clicked2)
        self.button2.move(200, 300)  # 设置按钮2的位置
        self.button2.hide()

        # self.button3 = QPushButton('3', self)
        # # self.button3.resize(100, 40)
        # #self.button3.clicked.connect(self.button_clicked3)
        # self.button3.move(200, 400)  # 设置按钮3的位置
        # self.button3.hide()

        # 创建播放WAV文件的按钮
        self.play_sound_button = QPushButton('播放声音', self)
        # self.play_sound_button.clicked.connect(self.playSound)
        self.play_sound_button.resize(100, 40)
        self.play_sound_button.move(200, 500)  # 设置按钮位置
        self.play_sound_button.hide()
        # 加载并应用QSS样式
        self.loadStyleSheet()

    def startGame(self):
        global last_choice, game_over, chat_history, outline, tone
        self.wav_index = self.wav_index + 1
        self.start_button.hide()
        self.play_sound_button.hide()
        self.name_input.hide()
        self.background_input.hide()
        self.style_input.hide()
        self.tone_input.hide()
        self.textedit.hide()

        name = self.name_input.text()
        background = self.background_input.text()  # 获取故事背景输入
        style = self.style_input.text()
        tone = self.tone_input.text()

        print("--  to get outline --")
        outline = generate_outline(name, background, style, tone)
        print("-- get outline --")
        scene_data, new_message = generate_game_content(outline, tone, chat_history, last_choice)
        scene_data = json.loads(scene_data)
        is_over = scene_data.get('is_over') == 'true'
        contents = scene_data.get('content')
        attribute = scene_data.get('attributes')

        print("--  to get picture --")
        generatePic(str(scene_data.get('image_prompt')))
        print(scene_data.get('image_prompt'))

        # print("--  to get picture --")
        # image_prompt = str(scene_data.get('image_prompt'))
        # thread_generatePic = threading.Thread(target=generatePic, args=(image_prompt,))
        # thread_generatePic.start()

        scene_content = "故事："

        for content in contents:
            if content['type'] == 1:
                # print("场景描述:", content['text'])
                scene_content = scene_content + "\n" + "    " + str(content['text'])
            else:
                character = content
                # print(f"{character['name']}: {character['dialogue']}")
                scene_content = scene_content + "\n" + str(character['name']) + " : " + str(character['dialogue'])
                wav_content = str(character['dialogue'])

                # 打印用户属性
        attributes = "当前健康值：" + str(attribute['health']) + "\n当前经验值：" + str(attribute['experience']) + "\n当前财富值：" + str(attribute['wealth'])
        # print(attributes)
        print("------- to get wav -------")
        getTextWav(wav_content, self.wav_index)
        print("-------- get wav")

        # print("------- to get wav -------")
        # thread_getTextWav = threading.Thread(target=getTextWav, args=(wav_content,))
        # thread_getTextWav.start()
        # # 等待两个线程完成
        # thread_generatePic.join()
        # thread_getTextWav.join()
        # print("-------- get wav")

        # print("可选选项:")
        i = 1
        for option in scene_data.get('options'):
            print(option['id'], option['text'])
            if i == 1:
                self.button1.setText(option['text'])
            if i == 2:
                self.button2.setText(option['text'])
            if i == 3:
                self.button3.setText(option['text'])
            i = i + 1

        # 更新聊天历史
        chat_history.append(new_message)

        game_over = is_over

        self.textedit.setText(attributes)


        self.story_edit.setText(scene_content)
        self.button1.show()
        self.button2.show()
        # self.button3.show()
        self.textedit.show()
        self.story_edit.show()
        self.play_sound_button.clicked.connect(self.playSound)
        self.play_sound_button.show()

        new_pixmap = QPixmap('./img/bg.png')  # 使用新的背景图片路径
        new_palette = QPalette()
        new_palette.setBrush(QPalette.Window,
                             QBrush(new_pixmap.scaled(self.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)))
        self.setPalette(new_palette)

    def button_clicked1(self):
        global last_choice, game_over, chat_history, outline
        last_choice = 1
        self.wav_index = self.wav_index + 1
        print(f"Button 1 clicked")
        scene_data, new_message = generate_game_content(outline, tone, chat_history, last_choice)
        scene_data = json.loads(scene_data)
        is_over = scene_data.get('is_over') == 'true'
        contents = scene_data.get('content')
        attribute = scene_data.get('attributes')

        print("--  to get picture --")
        generatePic(str(scene_data.get('image_prompt')))
        print(scene_data.get('image_prompt'))

        scene_content = "故事："

        for content in contents:
            if content['type'] == 1:
                # print("场景描述:", content['text'])
                scene_content = scene_content + "\n" + "    " + str(content['text'])
            else:
                character = content
                # print(f"{character['name']}: {character['dialogue']}")
                scene_content = scene_content + "\n" + str(character['name']) + " : " + str(character['dialogue'])
                wav_content = str(character['dialogue'])

                # 打印用户属性
        attributes = "当前健康值：" + str(attribute['health']) + "\n当前经验值：" + str(
            attribute['experience']) + "\n当前财富值：" + str(attribute['wealth'])
        # print(attributes)
        print("------- to get wav -------")
        getTextWav(wav_content, self.wav_index)
        print("-------- get wav")

        # print("可选选项:")
        i = 1
        for option in scene_data.get('options'):
            print(option['id'], option['text'])
            if i == 1:
                self.button1.setText(option['text'])
            if i == 2:
                self.button2.setText(option['text'])
            if i == 3:
                self.button3.setText(option['text'])
            i = i + 1

        # 更新聊天历史
        chat_history.append(new_message)

        game_over = is_over

        self.textedit.setText(attributes)


        self.story_edit.setText(scene_content)
        self.button1.show()
        self.button2.show()
        # self.button3.show()
        self.textedit.show()
        self.story_edit.show()
        self.play_sound_button.clicked.connect(self.playSound)
        self.play_sound_button.show()

        new_pixmap = QPixmap('./img/bg.png')  # 使用新的背景图片路径
        new_palette = QPalette()
        new_palette.setBrush(QPalette.Window,
                             QBrush(new_pixmap.scaled(self.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)))
        self.setPalette(new_palette)

    def button_clicked2(self):
        global last_choice, game_over, chat_history, outline, tone
        last_choice = 2
        self.wav_index = self.wav_index + 1
        print(f"Button 1 clicked")
        scene_data, new_message = generate_game_content(outline, tone, chat_history, last_choice)
        scene_data = json.loads(scene_data)
        is_over = scene_data.get('is_over') == 'true'
        contents = scene_data.get('content')
        attribute = scene_data.get('attributes')

        print("--  to get picture --")
        generatePic(str(scene_data.get('image_prompt')))
        print(scene_data.get('image_prompt'))

        scene_content = "故事："

        for content in contents:
            if content['type'] == 1:
                # print("场景描述:", content['text'])
                scene_content = scene_content + "\n" + "    " + str(content['text'])
            else:
                character = content
                # print(f"{character['name']}: {character['dialogue']}")
                scene_content = scene_content + "\n" + str(character['name']) + " : " + str(character['dialogue'])
                wav_content = str(character['dialogue'])

        attributes = "当前健康值：" + str(attribute['health']) + "\n当前经验值：" + str(
            attribute['experience']) + "\n当前财富值：" + str(attribute['wealth'])
        # print(attributes)
        print("------- to get wav -------")
        getTextWav(wav_content, self.wav_index)
        print("-------- get wav")

        i = 1
        for option in scene_data.get('options'):
            print(option['id'], option['text'])
            if i == 1:
                self.button1.setText(option['text'])
            if i == 2:
                self.button2.setText(option['text'])
            # if i == 3:
            #     self.button3.setText(option['text'])
            i = i + 1

        # 更新聊天历史
        chat_history.append(new_message)

        game_over = is_over

        self.textedit.setText(attributes)

        self.story_edit.setText(scene_content)
        self.button1.show()
        self.button2.show()
        # self.button3.show()
        self.textedit.show()
        self.story_edit.show()
        self.play_sound_button.clicked.connect(self.playSound)
        self.play_sound_button.show()

        new_pixmap = QPixmap('./img/bg.png')  # 使用新的背景图片路径
        new_palette = QPalette()
        new_palette.setBrush(QPalette.Window,
                             QBrush(new_pixmap.scaled(self.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)))
        self.setPalette(new_palette)

    def playSound(self):
        file_path = f'voice{self.wav_index}.wav'
        # print(file_path)
        player = SoundPlayer(file_path)
        player.play()

    def resizeEvent(self, event):
        super().resizeEvent(event)
        self.original_palette.setBrush(QPalette.Window, QBrush(self.original_pixmap.scaled(self.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)))
        if hasattr(self, 'new_pixmap'):
            self.new_palette.setBrush(QPalette.Window, QBrush(self.new_pixmap.scaled(self.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)))
        self.setPalette(self.new_palette if hasattr(self, 'new_pixmap') else self.original_palette)

    def loadStyleSheet(self):
        # 读取QSS文件
        file = QFile("./style.qss")
        if file.open(QFile.ReadOnly | QFile.Text):
            stream = QTextStream(file)
            style = stream.readAll()
            self.setStyleSheet(style)  # 应用样式
        file.close()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainwindow = MainWindow()
    mainwindow.show()
    sys.exit(app.exec_())